package com.permission.controller;

import com.permission.model.PageResult;
import com.permission.model.Role;
import com.permission.model.User;
import com.permission.service.RoleService;
import com.permission.service.UserService;
import com.permission.service.impl.RoleServiceImpl;
import com.permission.service.impl.UserServiceImpl;
import com.permission.util.WebUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private RoleService roleService = new RoleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        pathInfo = pathInfo == null ? "" : pathInfo;

        switch (pathInfo) {
            case "/search":
                searchUser(request, response);
                break;
            case "/searchPage":
                showSearchPage(request, response);
                break;
            case "/list":
                showUserListPage(request, response);
                break;
            case "/listData":
                getUserListData(request, response);
                break;
            case "/roles":
                showUserRolesPage(request, response);
                break;
            case "/saveRoles":
                saveUserRoles(request, response);
                break;
            default:
                WebUtil.redirect(request, response, "/index.jsp");
        }
    }

    // 显示用户查询页面
    private void showSearchPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/user/searchUser.jsp").forward(request, response);
    }

    // 查询用户及其角色
    private void searchUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = WebUtil.getParameter(request, "username");
        User user = userService.getUserWithRolesByUsername(username);
        request.setAttribute("user", user);
        request.getRequestDispatcher("/WEB-INF/jsp/user/userDetail.jsp").forward(request, response);
    }

    // 显示用户列表页面
    private void showUserListPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/user/userList.jsp").forward(request, response);
    }

    // 获取用户列表数据
    private void getUserListData(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String loginname = WebUtil.getParameter(request, "loginname");
        String email = WebUtil.getParameter(request, "email");
        Integer status = WebUtil.getIntParameter(request, "status");
        int pageNum = WebUtil.getIntParameter(request, "pageNum", 1);
        int pageSize = WebUtil.getIntParameter(request, "pageSize", 10);

        PageResult<User> result = userService.getUsersWithRolesAndMenus(loginname, email, status, pageNum, pageSize);

        ObjectMapper objectMapper = new ObjectMapper(); // 创建Jackson的JSON处理器
        String json = objectMapper.writeValueAsString(result); // 直接将PageResult对象序列化为JSON

        WebUtil.writeJson(response, json); // 保持原有的输出逻辑
    }

    // 显示用户角色设置页面
    private void showUserRolesPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long userId = WebUtil.getLongParameter(request, "userId");
        if (userId == null) {
            WebUtil.redirect(request, response, "/user/list");
            return;
        }

        User user = userService.getUserById(userId);
        List<Role> allRoles = roleService.getAllRoles();
        List<Role> userRoles = userService.getUserWithRolesByUsername(user.getLoginname()).getRoles();

        request.setAttribute("user", user);
        request.setAttribute("allRoles", allRoles);
        request.setAttribute("userRoles", userRoles);

        request.getRequestDispatcher("/WEB-INF/jsp/user/userRoles.jsp").forward(request, response);
    }

    // 保存用户角色设置
    private void saveUserRoles(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long userId = WebUtil.getLongParameter(request, "userId");
        String[] roleIdsStr = request.getParameterValues("roleIds");

        if (userId != null && roleIdsStr != null && roleIdsStr.length > 0) {
            List<Long> roleIds = Arrays.stream(roleIdsStr)
                    .map(Long::parseLong)
                    .collect(java.util.stream.Collectors.toList());

            userService.updateUserRoles(userId, roleIds);
        }

        WebUtil.redirect(request, response, "/user/list");
    }
}
